package com.example.demo;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer;
import org.springframework.amqp.rabbit.listener.adapter.MessageListenerAdapter;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;

@SpringBootApplication
public class TestMqApplication {

	@Value("${mq.topics}")
	private String mqTopic;

	public static void main(String[] args) {
		ApplicationContext context = SpringApplication.run(TestMqApplication.class, args);
		RabbitTemplate rabbitTemplate = context.getBean(RabbitTemplate.class);
		for(int i =0;i<100;i++){
			Map<String,Object> map = new HashMap<>();
			map.put("table","test");
			map.put("id",i);
			map.put("name","test"+i);
			rabbitTemplate.convertAndSend("test",map);
		}

		while (true){

		}
	}

	@Bean
	Queue queue(){
		return new Queue("test",true);
	}
	@Bean
	MessageListenerAdapter listenerAdapter(BeanMessageListener receiver) {
		return new MessageListenerAdapter(receiver, "receiveMessage");
	}

	@Bean
	SimpleMessageListenerContainer container(ConnectionFactory connectionFactory,
			MessageListenerAdapter listenerAdapter) {
		SimpleMessageListenerContainer container = new SimpleMessageListenerContainer();
		container.setConnectionFactory(connectionFactory);
		container.setQueueNames(Arrays.stream(mqTopic.split(","))
				.collect(Collectors.toList()).toArray(new String[]{}));
		container.setMessageListener(listenerAdapter);
		return container;
	}
}
